
    /**  
    * @Title: WordGenerateService.java
    * @Package com.efast.cafe.framework.word
    * @Description: TODO(用一句话描述该文件做什么)
    * @author Administrator
    * @date 2018年11月28日
    * @version V1.0  
    */
    
package com.efast.cafe.framework.freemarker;

import java.awt.Dimension;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Template;

/**
    * @ClassName: WordGenerateService
    * @Description: TODO(这里用一句话描述这个类的作用)
    * @author Administrator
    * @date 2018年11月28日
    *
    */
@Service
public class FreemarkerGenerateService {
	
	

	@Autowired
    private FreeMarkerConfigurer configurer;
	
	/**
	 * 生成word文档
	 * @param templateName
	 * @param outPath
	 * @param fileName
	 * @param params
	 * @return
	 */
	public String generateFileByTemplate(String templateName,String outPath,String fileName,Object params){
		//String fileName = UUID.randomUUID().toString();
		Writer out = null;
		String filePath = outPath+ File.separator + fileName;
		try{
			Map<String, Object> model = new HashMap<>();
			model.put("params", params);
			configurer.getConfiguration().setClassLoaderForTemplateLoading(Thread.currentThread().getContextClassLoader(), "template");
			configurer.getConfiguration().setDefaultEncoding("UTF-8");
			Template template = configurer.getConfiguration().getTemplate(templateName);
			 // 输出文件
	        File outFile = new File(filePath);
	        // 如果输出目标文件夹不存在，则创建
	        if (!outFile.getParentFile().exists()) {
	            outFile.getParentFile().mkdirs();
	        }
	        // 将模板和数据模型合并生成文件
	        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
	        template.process(model, out);
	        return filePath;
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			if(null!=out){
				 try {
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	
	
}
